package cn.itcast.crm.service.imp;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerDao;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;

@Service
@Transactional
public class CustomerServiceImp implements CustomerService {

	@Autowired
	private CustomerDao customerDao;

	@Override
	public List<Customer> findNoAssociationCustomers() {

		List<Customer> findByFixedAreaIdIsNull = customerDao.findByFixedAreaIdIsNull();
		return findByFixedAreaIdIsNull;
	}

	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(String fixedAreaId) {

		List<Customer> findByFixedAreaId = customerDao.findByFixedAreaId(fixedAreaId);
		return findByFixedAreaId;
	}

	@Override
	public void associationCustomersToFixedArea(String customerIds, String fixedAreaId) {
		customerDao.jiechouguanlian(fixedAreaId);
		if (StringUtils.isNotBlank(customerIds)) {
			List<Integer> toIntArr = parseStringArrToIntArr(customerIds.split(","));
			for (Integer id : toIntArr) {
				customerDao.updateFixedAreaId(fixedAreaId, id);
			}
		}

	}

	private List<Integer> parseStringArrToIntArr(String[] customerIdStr) {
		// 处理客户Id
		List<Integer> intArr = new ArrayList<Integer>();
		for (String str : customerIdStr) {
			try {
				intArr.add(NumberUtils.toInt(str, 10));
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		return intArr;

	}

	@Override
	public void saveCustomer(Customer customer) {
		customerDao.save(customer);

	}

	@Override
	public Customer findByTelephone(String telephone) {
		return customerDao.findByTelephone(telephone);
	}

	@Override
	public void updateType(String telephone) {
		customerDao.updateType(telephone);
	}

	//登录
	@Override
	public Customer findByTelephoneAndPassword(String telephone, String password) {
		Customer customer= customerDao.findByTelephoneAndPassword(telephone,password);
		return customer;
	}

	@Override
	public String findFixedAreaIdByAddress(String sendAddress) {
		
		return customerDao.findFixedAreaIdByAddress(sendAddress);
	}

}
